package cn.bj.ykct.web;

import java.io.File;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UploadController {

	@RequestMapping(value = "/toUpload", method = RequestMethod.GET)
	public String toUpload() {
		return "/upload";
	}

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String upload(Model model, @RequestParam(name = "name", required = true) String name,
			@RequestParam(value = "aFile", required = true) MultipartFile aFile) {

		String temppath = "C:/upload";
		try {
			File tempFile = new File(temppath);
			if (!tempFile.exists()) {
				tempFile.mkdirs();
			}

			String filename = aFile.getName();
			filename = filename.substring(filename.lastIndexOf("\\") + 1, filename.length());
			File uploadFile = new File(temppath + "/" + filename);
			aFile.transferTo(uploadFile);

			model.addAttribute("uploadResult", "Hi, " + name + ", your file is uploaded.");
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("uploadResult", "upload error");
		}
		return "/upload";
	}
}
